package com.ruoyi.api.activiti.listener;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.activiti.mapper.BizTodoItemMapper;
import com.ruoyi.api.activiti.service.UsualWrokService;
import com.ruoyi.api.mqtt.MqttService;
import com.ruoyi.api.wsmessage.domain.Wsmessage;
import com.ruoyi.api.wsmessage.mapper.WsmessageMapper;
import com.ruoyi.api.wsmessage.service.IWsmessageService;
import com.ruoyi.api.wsmessage.service.impl.WsmessageServiceImpl;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.cache.user.UserCacheService;
import com.ruoyi.system.domain.SysUser;
import com.ruoyi.system.service.ISysUserService;
import lombok.extern.slf4j.Slf4j;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.delegate.DelegateTask;
import org.activiti.engine.delegate.TaskListener;
import org.activiti.engine.impl.el.FixedValue;
import org.activiti.engine.runtime.ProcessInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;

@Service("taskCreateListener")
@Slf4j
public class TaskCreateListener implements TaskListener {
  private FixedValue assignments;
  private FixedValue headDept;
  public void setAssignments(FixedValue assignments) {
      this.assignments = assignments;
  }
  public void setHeadDept(FixedValue headDept) {
    this.headDept = headDept;
  }

  @Autowired
  private BizTodoItemMapper bizTodoItemMapper;
  @Autowired
  private MqttService mqttService;
  @Autowired
  private ISysUserService userService;
  @Autowired
  private UserCacheService userCacheService;
  @Autowired
  private RuntimeService runtimeService;
  @Autowired
  private UsualWrokService usualWrokService;
  @Autowired
  private TaskService taskService;
  @Override
  public void notify(DelegateTask delegateTask) {
    if(delegateTask.getEventName().equals(TaskListener.EVENTNAME_ASSIGNMENT)){
//      String assignee = delegateTask.getAssignee();
//      handleBiz(assignee,delegateTask);
      return;
    }
    if(!delegateTask.getEventName().equals(TaskListener.EVENTNAME_CREATE))return;

    String assignee = assignments.getExpressionText();
    Map<String, Object> variables = delegateTask.getVariables();
    Object frontAssign = variables.get("frontAssign");
    if(frontAssign !=null){
      assignee=String.valueOf(frontAssign);
      delegateTask.setAssignee(assignee);
      delegateTask.removeVariable("frontAssign");
      JSONObject jsonObject = updateApplyEntity(assignee,delegateTask);
      if (jsonObject == null) return;
      sendTaskMsg(assignee,delegateTask,jsonObject,0);

    }else{
      if(StringUtils.isEmpty(assignee)){
        return;
      }
      if(assignee.startsWith("user_")){
        assignee=assignee.replace("user_","");
        delegateTask.setAssignee(assignee);
        JSONObject jsonObject = updateApplyEntity(assignee,delegateTask);
        if (jsonObject == null) return;
        sendTaskMsg(assignee,delegateTask,jsonObject,0);
      }else if(assignee.startsWith("group_")){
        String groupId=assignee.replace("group_","");
        Object projectId=null;
        if(headDept==null ||StringUtils.isEmpty(headDept.getExpressionText())){
          projectId = variables.get("projectId");
        }
        List<String> users=null;
        if(projectId!=null){
          users= bizTodoItemMapper.selectTodoUserListByGroupId1(groupId, String.valueOf(projectId));
        }else {
          users= bizTodoItemMapper.selectTodoUserListByGroupId2(groupId);
        }
        if(users !=null && users.size() > 0){
          for(String user:users){
            delegateTask.addCandidateUser(user);
            if(users.size() == 1){
              JSONObject jsonObject = updateApplyEntity(user,delegateTask);
              if (jsonObject == null) return;
              sendTaskMsg(user,delegateTask,jsonObject,0);
            }else {
              JSONObject jsonObject = updateApplyEntity(null,delegateTask);
              if (jsonObject == null) return;
              sendTaskMsg(user,delegateTask,jsonObject,1);
            }
          }
        }
      }
    }
  }

  private JSONObject updateApplyEntity(String assignee,DelegateTask delegateTask) {
    Map<String, Object> variables = delegateTask.getVariables();
    String service = variables.get("service") !=null ?String.valueOf(variables.get("service")):null;
    String suspendState = variables.get("suspendState") !=null ?String.valueOf(variables.get("suspendState")):null;
    Integer approved = variables.get("approved")!=null ?Integer.valueOf(String.valueOf(variables.get("approved"))):null;
    String instanceId = delegateTask.getProcessInstanceId();
    JSONObject jsonObject = null;
    ProcessInstance processInstance = runtimeService.createProcessInstanceQuery().processInstanceId(instanceId)
      .includeProcessVariables().active().singleResult();
    String businessKey = null;
    if (processInstance != null) {
      businessKey = processInstance.getBusinessKey();
    }else{
      businessKey=String.valueOf(variables.get("businessKey"));
    }
    if(StringUtils.isEmpty(businessKey)||StringUtils.isEmpty(service)) return null;

    jsonObject = usualWrokService.getBaseVo(service, businessKey);
    if (StringUtils.isEmpty(jsonObject.getString("id"))) {
      log.error("instanceId==" + instanceId + ",业务实例expenseReport非法");
      return null;
    }
    jsonObject.put("taskId", delegateTask.getId());
    jsonObject.put("instanceId", instanceId);
    if (approved !=null && approved == 0) {
      jsonObject.put("suspendState", "4");
    }else if(approved !=null && approved == 1){
      if(!StringUtils.isEmpty(suspendState) && suspendState.equalsIgnoreCase("4")){
        jsonObject.put("suspendState", "1");
      }
    }else {
      jsonObject.put("suspendState", "1");
    }

    jsonObject.put("taskName", delegateTask.getName());
    if(!StringUtils.isEmpty(assignee)){
      SysUser sysUser = userService.selectUserByLoginName(assignee);
      if(sysUser!=null){
        jsonObject.put("taskName", "等待 "+sysUser.getUserName()+" 完成审批");
      }
    }
    jsonObject.put("endTime", System.currentTimeMillis());
    usualWrokService.update(jsonObject.toJSONString(), 1,service);
    return jsonObject;
  }
  @Autowired
  private IWsmessageService wsmessageService;

  private void sendTaskMsg(String assignee, DelegateTask delegateTask, JSONObject jsonObject,int flag) {
    Map<String, Object> variables = delegateTask.getVariables();
    String service = variables.get("service") !=null ?String.valueOf(variables.get("service")):null;
    String instanceId = delegateTask.getProcessInstanceId();
    String createrId = jsonObject.getString("createrId");
    SysUser userSender=userCacheService.getUserInfo(Long.parseLong(createrId));
    if (StringUtils.isEmpty(createrId)) {
      return;
    }
    try {
      String taskName=jsonObject.getString("taskName");
      String applyState=jsonObject.getString("suspendState");
      String applyType=null;
      String applyTypeName=null;
      if(service.equalsIgnoreCase("expense")){
        applyType="maintain";
        applyTypeName="维修费用申请";
      }else if(service.equalsIgnoreCase("applyassets")){
        applyType="applyassets";
        applyTypeName="资产设备申请";
      }
      Wsmessage wsmessage = buildWsmessage(assignee, instanceId, jsonObject, createrId, userSender, taskName, applyState, applyType, applyTypeName,flag);
      wsmessageService.UpdateAllByinstanceId(wsmessage);
      mqttService.sendMessage(1,wsmessage);//存在则更新，不存在就插入

    }catch (Exception e){
     e.printStackTrace();
    }
  }

  private Wsmessage buildWsmessage(String assignee, String instanceId, JSONObject jsonObject, String createrId, SysUser userSender, String taskName, String applyState, String applyType, String applyTypeName,int flag) {
    Wsmessage wsmessage=new Wsmessage();
    wsmessage.setRole("driver");

    wsmessage.setType(applyType);
    wsmessage.setTypeName(applyTypeName);
    wsmessage.setTitle(String.valueOf(jsonObject.getString("title")));
    wsmessage.setEntityId(String.valueOf(jsonObject.getString("id")));
    wsmessage.setInstanceId(instanceId);
    wsmessage.setTaskName(taskName);
    wsmessage.setApplyState(applyState);

    wsmessage.setUserSenderId(Long.parseLong(createrId));
    wsmessage.setUserSenderName(userSender.getUserName());
    Long createTime = jsonObject.getLong("createTime");
    wsmessage.setSubmitTime(new Date(createTime));

    wsmessage.setUserReceiverLoginName(assignee);
    SysUser receiverUser = userService.selectUserByLoginName(assignee);
    wsmessage.setUserReceiverName(receiverUser.getUserName());
    if(!StringUtils.isEmpty(wsmessage.getUserReceiverName()) && flag == 0){
      wsmessage.setTaskName("等待 "+wsmessage.getUserReceiverName()+" 审批");
    }else {
      wsmessage.setTaskName(taskName);
    }
    return wsmessage;
  }

}
